/**
 * Created by huangchengyong on 2016/8/26.
 */
//追加入库商品
var rownum = 1;
function additional() {
    //var rownum = $("#skubox").children().length;
    var id = 'product'+(rownum+1);
    var html  = '<tr>';
        html += '<input type="hidden" class="sku_pid" value="">';
        html += '<input type="hidden" class="sku_name" value="">';
        html += '<input type="hidden" class="sku_skuattr" value="">';
        html += '<input type="hidden" class="sku_mass_packing" value="">';
        html += '<input type="hidden" class="sku_individual_packing" value="">';
        html += '<td data-title="序号"><input type="hidden" class="sku_id" value="">'+(rownum+1)+'</td>';
        //html += '<td data-title="商品" class="name" href="#myModal" data-toggle="modal" onclick="getnum(this)"></td>';
        html += '<td data-title="商品" style="padding: 0px"><input type="text" autocomplete="off" class="productname" id="product'+(rownum+1)+'" onclick="getProduct(this)" value="" placeholder=" 请输入商品名称" style="height: 44px;width: 100%;border: 0px"></td>';
        html += '<td data-title="入库数量" style="padding: 0px"><input type="text" class="inconum" value="" onkeyup="changeFocus(this)" style="height: 44px;width: 100%;border: 0px"></td>';
        html += '<td data-title="备注" style="padding: 0px"><input type="text" class="skuremark" value="" onkeyup="changeFocus(this)" style="height: 44px;width: 100%;border: 0px"></td>';
        html += '<td data-title="操作"><a onclick="delsku(this)"><img src="/assets/images/delicon.png" class="icon-padding"/>删除</a></td>';
        html += '</tr>';
    $("#skubox").append(html);
    rownum ++;
    return id;
}
//删除行
function delsku(obj) {
    $(obj).parent().parent().remove();
}

function getnum(obj) {
    $(".skuid").attr('checked',false);
    var thisnum = $(obj).parent().index();
    $("#rows").val(thisnum);
}

//全选
$(document).on('click','#checkAll',function(){
    $('.skuid').attr("checked",this.checked);
});

function checkSku() {
    var skudata = {};
    var key;
    var checknum = $(".skuid:checked").length;
    $("#enterprisesku").find('tr').each(function(i,n){
        if($(this).find('.skuid').is(':checked')){
            skudata[i] = [];
            var skuid = $(this).find('.skuid').val();
            var name = $(this).find('.name').text();
            var attr = $(this).find('.attr').text();
            var pid = $(this).find('.pid').val();
            var mass_packing = $(this).find('.mass_packing').val();
            var individual_packing = $(this).find('.individual_packing').val();

            skudata[i]['skuid'] = skuid;
            skudata[i]['name'] = name;
            skudata[i]['attr'] = attr;
            skudata[i]['pid'] = pid;
            skudata[i]['mass_packing'] = mass_packing;
            skudata[i]['individual_packing'] = individual_packing;
            key = i;
        }
    });

    if (checknum == 1) {
        var rows = $("#rows").val();
        $("#skubox").find('tr').eq(rows).find('.name').text(skudata[key]['name']);
        $("#skubox").find('tr').eq(rows).find('.sku_id').val(skudata[key]['skuid']);
        $("#skubox").find('tr').eq(rows).find('.sku_pid').val(skudata[key]['pid']);
        $("#skubox").find('tr').eq(rows).find('.sku_name').val(skudata[key]['name']);
        $("#skubox").find('tr').eq(rows).find('.sku_skuattr').val(skudata[key]['attr']);
        $("#skubox").find('tr').eq(rows).find('.sku_mass_packing').val(skudata[key]['mass_packing']);
        $("#skubox").find('tr').eq(rows).find('.sku_individual_packing').val(skudata[key]['individual_packing']);
    } else if (checknum > 1) {
        //如果一次添加多条，先去掉默认的一条
        var rows = $("#rows").val();
        $("#skubox").find('tr').eq(rows).remove();
        //$("#skubox").html('');
        var html = '';
        //var rownum = 1
        var rownum = $("#skubox").children().length;
        $.each(skudata,function(k,v){
            rownum ++;
            html += '<tr>';
            html += '<input type="hidden" class="sku_pid" value="'+v['pid']+'">';
            html += '<input type="hidden" class="sku_name" value="'+v['name']+'">';
            html += '<input type="hidden" class="sku_skuattr" value="'+v['attr']+'">';
            html += '<input type="hidden" class="sku_mass_packing" value="'+v['mass_packing']+'">';
            html += '<input type="hidden" class="sku_individual_packing" value="'+v['individual_packing']+'">';
            html += '<td data-title="序号"><input type="hidden" class="sku_id" value="'+v['skuid']+'">'+rownum+'</td>';
            html += '<td data-title="商品" class="name" href="#myModal" data-toggle="modal" onclick="getnum(this)">'+v['name']+'</td>';
            html += '<td data-title="入库数量" style="padding: 0px"><input type="text" class="inconum" value="" style="height: 44px;width: 100%;border: 0px"></td>';
            html += '<td data-title="备注" style="padding: 0px"><input type="text" class="skuremark" value="" style="height: 44px;width: 100%;border: 0px"></td>';
            html += '<td data-title="操作"><a class="btn btn-danger btn-xs" onclick="delsku(this)">删除</a></td>';
            html += '</tr>';
        });
        $("#skubox").append(html);
    }
}

//选择商品方案二
function getProduct(obj){
    var id = $(obj).attr('id');
    var _this = '#'+id;

    $(_this).typeahead({
        items:10,
        source:function(query,process) {
            $.ajax({
                url: '/warehouse/addincoming',
                type: 'POST',
                dataType: 'JSON',
                async: true,
                data: {'type':'getprouct',key:query} ,
                success: function (info) {
                    var msg = info.msg;
                    var res = info.res;
                    if(msg=='success') {
                        window.rows = [];
                        var isSku = [];
                        $('#skubox').find('tr').each(function(){
                            var id = $(this).find('.sku_id').val();
                            isSku.push(id);
                        });
                        for (i in res){
                            if(isSku.indexOf(res[i].id)>=0){
                                continue;
                            }
                            rows.push(res[i]);
                        }
                        var results = rows.map(function (row) {
                            return JSON.stringify(row);
                        });
                        process(results);
                    }
                }
            });
        },
        matcher: function (obj) {
            var item = JSON.parse(obj);
            return ~item.name.toLowerCase().indexOf(this.query.toLowerCase())
        },
        sorter: function (items) {
            var beginswith = [], caseSensitive = [], caseInsensitive = [], item;
            while (aItem = items.shift()) {
                var item = JSON.parse(aItem);
                if (!item.name.toLowerCase().indexOf(this.query.toLowerCase()))
                    beginswith.push(JSON.stringify(item));
                else if (~item.name.indexOf(this.query)) caseSensitive.push(JSON.stringify(item));
                else caseInsensitive.push(JSON.stringify(item));
            }
            return beginswith.concat(caseSensitive, caseInsensitive)

        },
        highlighter: function (obj) {
            var item = JSON.parse(obj);
            var query = this.query.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&')
            return item.name.replace(new RegExp('(' + query + ')', 'ig'), function ($1, match) {
                    return '<strong>' + match + '</strong>'
                }) + item.attr;
        },
        updater:function (obj) {
            var item = JSON.parse(obj);
            $(_this).parent().parent().find('.sku_id').val(item.id);
            $(_this).parent().parent().find('.sku_pid').val(item.pid);
            $(_this).parent().parent().find('.sku_name').val(item.name);
            $(_this).parent().parent().find('.sku_skuattr').val(item.attr);
            $(_this).parent().parent().find('.sku_mass_packing').val(item.mass_packing);
            $(_this).parent().parent().find('.sku_individual_packing').val(item.individual_packing);

            return item.name+item.attr;
        }
    });

    $(_this).keyup(function(e){
        if(e.which==13){
            $(obj).parent().parent().find('.inconum').focus().select();
            var name = $(obj).parent().parent().find('.sku_name').val();
            checkReSku(name,_this);
        }
    });
}
$(document).on('click','.inconum',function(){
    var id = $(this).parent().parent().find('.productname').attr('id');
    var name = $(this).parent().parent().find('.sku_name').val();
    checkReSku(name,'#'+id);
});
function checkReSku(name,e) {
    $.ajax({
        url: '/warehouse/addincoming',
        type: 'POST',
        dataType: 'JSON',
        async: true,
        data: {'type':'isThatSku',key:name} ,
        success: function (info) {
            var msg = info.msg;
            if(msg=='error'){
                //layer.tips('暂无该商品',e);
                //return false;
                layer.tips('提示：请在搜索出的列表中选择商品，并按回车键确认！其他任何形式输入的商品无效。',e, {
                    tips: [1, '#FF9999'],
                    time: 10000
                });
            }
        }
    });
}

function changeFocus(obj) {
    if(navigator.appName == "Microsoft Internet Explorer"){
        var keycode = event.keyCode;
    }else{
        var keycode =  changeFocus.caller.arguments[0].which;
    }
    if(keycode == 13){
        var num = $(obj).parent().parent().nextAll().length;
        if(num == 0){
            var id = additional();
            $("#"+id).click();
            $(obj).parent().parent().next().find('.productname').focus().select();
            //商品数量输入框得到焦点后验证商品是否存在

        } else {
            $(obj).parent().parent().next().find('.productname').focus().select();
        }
    }
}

//保存数据
function savedata() {
    var warehouse = $("#warehouse").val();
    var number = $("#number").val();
    var incoming_type = $("#incoming_type").val();
    var incoming_time = $("#incoming_time").val();
    var mange_id = $("#mange_id").val();
    var mange_name = $("#mange_name").val();
    var remark = $("#remark").val();
    var skudata = [];
    $("#skubox").find('tr').each(function(k,v){
        var skuid = $(this).find('.sku_id').val();
        var inconum = $(this).find('.inconum').val();
        var skuremark = $(this).find('.skuremark').val();
        var name = $(this).find('.sku_name').val();
        var pid = $(this).find('.sku_pid').val();
        var skuattr = $(this).find('.sku_skuattr').val();
        var mass_packing = $(this).find('.sku_mass_packing').val();
        var individual_packing = $(this).find('.sku_individual_packing').val();
        if(skuid){
            var tmp = {};
            tmp['id'] = skuid;
            tmp['inconum'] = inconum;
            tmp['skuremark'] = skuremark;
            tmp['name'] = name;
            tmp['pid'] = pid;
            tmp['attr'] = skuattr;
            tmp['mass_packing'] = mass_packing;
            tmp['individual_packing'] = individual_packing;
            skudata.push(tmp);
        }
    });
    for(var i in skudata){
        if(!skudata[i].inconum){
            layer.alert('请填写入库数量','.inconum');return false;
        }
    }
    if(!warehouse){
        layer.tips('请选择仓库', '#Warehouse');return false;
    }
    if(!incoming_type){
        layer.tips('请选择入库类型', '#incoming_type');return false;
    }
    if(!incoming_time){
        layer.tips('请选择入库日期', '#incoming_time');return false;
    }
    if(!mange_name){
        layer.tips('缺少制单人信息', '#mange_name');return false;
    }

    if(skudata.length == 0){
        layer.alert('请至少添加一个商品');return false;
    }else{
        skudata = JSON.stringify(skudata);
    }

    $.ajax({
        url : '/warehouse/insertincoming',
        type : 'post',
        data : {warehouse:warehouse,number:number,incoming_type:incoming_type,incoming_time:incoming_time,mange_id:mange_id,mange_name:mange_name,remark:remark,skudata:skudata},
        dataType : 'json',
        beforeSend:function(){
            var index = layer.load(2, {
                shade: [0.5,'#fff'] //0.1透明度的白色背景
            });
        },
        success : function (msg) {
            if(msg.msg == 'ok') {
                layer.alert('入库成功',function () {
                    window.location.reload();
                });
            }
        }
    });
}

